@echo off
chcp 65001 > nul
setlocal EnableDelayedExpansion

:: 设置服务器信息
set SERVER_USER=root
set SERVER_HOST=linchaochao.com
set SERVER_PORT=22
set REMOTE_JAR_NAME=new-0.0.1-SNAPSHOT.jar
set SERVICE_FILE=/etc/systemd/system/recruitment.service

echo [信息] 开始配置后端守护进程...
echo.

:: 创建本地临时服务文件
echo [信息] 生成服务配置文件...
(
  echo [Unit]
  echo Description=Recruitment Java Application
  echo After=network.target
  echo.
  echo [Service]
  echo Type=simple
  echo User=root
  echo Environment="JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64"
  echo Environment="SPRING_PROFILES_ACTIVE=prod"
  echo WorkingDirectory=/home/backend
  echo ExecStart=/usr/bin/java -jar %REMOTE_JAR_NAME%
  echo SuccessExitStatus=143
  echo TimeoutStopSec=10
  echo Restart=on-failure
  echo RestartSec=5
  echo.
  echo [Install]
  echo WantedBy=multi-user.target
) > recruitment.service

if %ERRORLEVEL% neq 0 (
    echo [错误] 服务文件生成失败
    goto :error
)
echo [成功] 服务配置文件已生成
echo.

:: 上传服务配置文件
echo [信息] 上传服务配置文件到服务器...
scp -P %SERVER_PORT% recruitment.service %SERVER_USER%@%SERVER_HOST%:%SERVICE_FILE%
if %ERRORLEVEL% neq 0 (
    echo [错误] 服务文件上传失败
    goto :error
)
echo [成功] 服务配置文件已上传
echo.

:: 重启服务并明确显示状态
echo [信息] 正在重启服务...
ssh -T -p %SERVER_PORT% -o LogLevel=ERROR %SERVER_USER%@%SERVER_HOST% "
    echo '>>> 执行 systemctl daemon-reload' &&
    systemctl daemon-reload &&
    echo '>>> 启用开机自启' &&
    systemctl enable recruitment.service &&
    echo '>>> 重启服务' &&
    systemctl restart recruitment.service &&
    echo '>>> 等待服务启动...' &&
    sleep 5 &&
    echo '>>> 服务状态：' &&
    systemctl status recruitment.service --no-pager &&
    exit
" > ssh_output.log 2>&1

if %ERRORLEVEL% neq 0 (
    echo [错误] 服务重启失败！请检查 ssh_output.log 文件。
    goto :error
)
echo [成功] 服务已正常重启
echo.

:: 清理临时文件
:cleanup
if exist recruitment.service del recruitment.service > nul

echo [成功] 守护进程配置完成！
echo.
echo [提示] 您可以通过以下命令手动检查服务状态：
echo        ssh -p %SERVER_PORT% %SERVER_USER%@%SERVER_HOST% "systemctl status recruitment.service"
echo.
pause
exit /b 0

:error
echo.
echo [错误] 流程执行失败！
call :cleanup
pause
exit /b 1